<template>
  <section class="login-page">
    <div class="login-box">
      <div class="title">用户登录</div>
      <div class="login-form">
        <el-select v-model="form.role" size="small" placeholder="请选择角色" class="!w-80%">
          <el-option
            v-for="roleItem in roleList"
            :key="roleItem.code"
            :label="roleItem.name"
            :value="roleItem.code"
          />
        </el-select>
        <div class="login-line" />
        <el-button
          :disabled="loading"
          :loading="loading"
          size="small"
          class="login-btn"
          @click="signIn"
          >登 录</el-button
        >
      </div>
      <div class="login-tip"
        >推荐使用最新版本谷歌浏览器, 确保页面内容显示正常<br />页面分辨率为1920 x 1080</div
      >
    </div>
  </section>
</template>

<script setup lang="ts">
import { UserType } from '@/api/login/types'
import { loginApi } from '@/api/login'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'

defineOptions({
  name: 'Login'
})

const form = reactive({
  role: 'role1'
} as UserType)

const roleList = reactive([
  {
    name: '企业\机构角色',
    code: 'role1'
  },
  {
    name: '审核机构',
    code: 'role2'
  }
])

const loading = ref(false)

const userStore = useUserStore()
const permissionStore = usePermissionStore()
const { currentRoute, addRoute, push } = useRouter()

// 登录
const signIn = async () => {
  try {
    const res = await loginApi(form)
    if (res) {
      userStore.setUserInfo(res.data)
      userStore.setToken(res.data.token)
      await permissionStore.generateRoutes('static').catch(() => {})
      permissionStore.getAddRouters.forEach((route) => {
        addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
      })
      permissionStore.setIsAddRouters(true)
      push({ path: redirect.value || '/' })
    }
  } finally {
    loading.value = false
  }
}

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
</script>
